<template>
  <div class="data-table-container">
    <div class="table-header">
      <div class="title">{{ title }}</div>
      <div class="table-actions">
        <el-tooltip content="刷新表格数据" placement="top">
          <el-button type="primary" size="small" icon="Refresh" circle @click="refreshData" />
        </el-tooltip>
        <el-tooltip content="导出数据" placement="top">
          <el-button type="success" size="small" icon="Download" circle @click="exportData" />
        </el-tooltip>
      </div>
    </div>

    <el-table
      ref="tableRef"
      :data="tableData"
      style="width: 100%"
      height="calc(100% - 85px)"
      border
      stripe
      :highlight-current-row="false"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      row-key="id"
    >
      <!-- 选择列 -->
      <el-table-column v-if="showSelection" type="selection" width="50" align="center" />

      <!-- 数据列 -->
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :sortable="column.sortable"
        :align="column.align || 'left'"
      >
        <template #default="scope">
          <!-- 处理特殊数据类型 -->
          <template v-if="column.type === 'date'">
            {{ formatDate(scope.row[column.prop]) }}
          </template>
          <template v-else-if="column.type === 'boolean'">
            <el-tag :type="scope.row[column.prop] ? 'success' : 'info'">
              {{ scope.row[column.prop] ? '是' : '否' }}
            </el-tag>
          </template>
          <template v-else>
            {{ scope.row[column.prop] }}
          </template>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column v-if="showActions" label="操作" width="120" fixed="right" align="center">
        <template #default="scope">
          <el-tooltip content="查看详情" placement="top">
            <el-button
              type="primary"
              size="small"
              icon="View"
              circle
              @click="handleView(scope.row)"
            />
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              circle
              @click="handleEdit(scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>

      <!-- 自定义行模板 -->
      <template #row="{ row, $index }">
        <tr
          :data-row-id="row.id"
          :class="{
            'highlighted-row': row.id === highlightedRowId,
            'selected-row': selectedRowIds.includes(row.id),
          }"
        >
          <td v-for="column in columns" :key="column.prop" :align="column.align || 'left'">
            {{ row[column.prop] }}
          </td>
        </tr>
      </template>

      <!-- 空状态 -->
      <template #empty>
        <div class="empty-content">
          <el-empty :description="emptyText" />
        </div>
      </template>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container" v-if="showPagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalItems"
        :layout="paginationLayout"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 定位行状态 -->
    <transition name="el-fade-in-linear">
      <div class="locate-status" v-if="locateStatus.visible">
        <el-alert
          :title="locateStatus.message"
          :type="locateStatus.type"
          :closable="false"
          center
          show-icon
        />
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { componentRegistry } from '@/services/ComponentRegistry'
import type { TableColumn } from './types'

// 组件属性
const props = withDefaults(
  defineProps<{
    componentId: string // 组件唯一ID
    title?: string // 表格标题
    columns: TableColumn[] // 表格列配置
    showPagination?: boolean // 是否显示分页
    showActions?: boolean // 是否显示操作列
    showSelection?: boolean // 是否显示选择列
    apiUrl?: string // 数据API地址
    paginationLayout?: string // 分页布局
    emptyText?: string // 空数据文本
  }>(),
  {
    title: '数据列表',
    showPagination: true,
    showActions: true,
    showSelection: true,
    apiUrl: '',
    paginationLayout: 'total, sizes, prev, pager, next, jumper',
    emptyText: '暂无数据',
  },
)

// 组件状态
const tableRef = ref<any>()
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(0)
const highlightedRowId = ref<string | number | null>(null)
const sortProp = ref('')
const sortOrder = ref('')
const locateStatus = ref({
  visible: false,
  message: '',
  type: 'success',
})

// 计算属性
const selectedRowIds = computed(() => selectedRows.value.map((r) => r.id))

// 格式化日期
const formatDate = (date: string | Date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 处理行选择
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 处理排序
const handleSortChange = ({ prop, order }: any) => {
  sortProp.value = prop
  sortOrder.value = order
  loadData()
}

// 处理查看操作
const handleView = (row: any) => {
  console.log('查看行数据:', row)
  ElMessage.info(`查看 ${row.id} 的详细信息`)
}

// 处理编辑操作
const handleEdit = (row: any) => {
  console.log('编辑行数据:', row)
  ElMessage.warning(`编辑 ${row.id} 的数据`)
}

// 处理分页大小变化
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  loadData()
}

// 处理当前页变化
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  loadData()
}

// 导出数据
const exportData = () => {
  ElMessage.success('数据导出功能已触发')
  // 这里可以添加实际导出逻辑
}

// 刷新数据
const refreshData = (force = false) => {
  currentPage.value = 1
  loadData(force)
}

// 加载数据
const loadData = async (force = false) => {
  try {
    // 这里应该是实际的API调用
    // 模拟API延迟
    await new Promise((resolve) => setTimeout(resolve, 500))

    // 生成模拟数据
    const newData = []
    const startIndex = (currentPage.value - 1) * pageSize.value

    for (let i = 0; i < pageSize.value; i++) {
      const id = startIndex + i + 1
      newData.push({
        id: `item-${id}`,
        name: `项目 ${id}`,
        category: ['科技', '教育', '医疗', '金融'][id % 4],
        status: ['进行中', '已完成', '已取消'][i % 3],
        priority: ['高', '中', '低'][i % 3],
        created: new Date(Date.now() - Math.random() * 10000000000).toISOString(),
        progress: Math.floor(Math.random() * 100),
      })
    }

    tableData.value = newData
    totalItems.value = 300 // 模拟总数据量
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

// 定位行
const locateRow = async (rowId: string | number) => {
  try {
    // 清除之前的高亮
    highlightedRowId.value = null

    // 尝试查找行
    const rowIndex = tableData.value.findIndex((row) => row.id === rowId)

    if (rowIndex === -1) {
      // 如果当前页找不到，尝试加载包含该行的页面
      // 实际项目中应该根据ID计算出所在页面
      const targetPage = Math.floor(Math.random() * 10) + 1
      currentPage.value = targetPage
      await loadData()

      // 再次尝试查找
      const newIndex = tableData.value.findIndex((row) => row.id === rowId)
      if (newIndex === -1) {
        throw new Error(`未找到行ID: ${rowId}`)
      }

      scrollToRow(newIndex)
    } else {
      scrollToRow(rowIndex)
    }

    // 高亮该行
    highlightedRowId.value = rowId

    // 显示定位成功消息
    showLocateStatus(`成功定位到行: ${rowId}`, 'success')

    return true
  } catch (error: any) {
    console.error('定位行失败:', error)
    showLocateStatus(`定位失败: ${error.message || '未知错误'}`, 'error')
    return false
  }
}

// 滚动到指定行
const scrollToRow = async (index: number) => {
  await nextTick()

  if (tableRef.value && tableRef.value.$el) {
    const tableBody = tableRef.value.$el.querySelector('.el-table__body-wrapper')
    if (!tableBody) return

    // 计算目标行位置（假设每行高度为48px）
    const rowHeight = 48
    const scrollPosition = Math.max(0, index * rowHeight - 200) // 保留顶部空间

    // 平滑滚动到位置
    tableBody.scrollTo({
      top: scrollPosition,
      behavior: 'smooth',
    })
  }
}

// 显示定位状态
const showLocateStatus = (message: string, type: 'success' | 'error' | 'warning') => {
  locateStatus.value = {
    visible: true,
    message,
    type,
  }

  // 5秒后自动隐藏
  setTimeout(() => {
    locateStatus.value.visible = false
  }, 5000)
}

// 生命周期钩子
onMounted(async () => {
  // 注册组件
  componentRegistry.register(props.componentId, getCurrentInstance()!.proxy!, {
    description: `${props.title} - 数据表格`,
    type: 'data-table',
  })

  // 加载初始数据
  await loadData()

  console.log(`表格组件 ${props.componentId} 已注册并加载`)
})

onUnmounted(() => {
  // 注销组件
  componentRegistry.unregister(props.componentId)
})

// 暴露公共API（供命令系统使用）
defineExpose({
  locateRow,
  refreshData,
  loadData,
})
</script>

<style scoped lang="scss">
.data-table-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  overflow: hidden;
  position: relative;

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;

    .title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }

    .table-actions {
      display: flex;
      gap: 8px;
    }
  }

  .pagination-container {
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: flex-end;
  }

  .empty-content {
    padding: 40px 0;
  }

  .locate-status {
    position: absolute;
    top: 60px;
    left: 0;
    right: 0;
    z-index: 10;
    padding: 0 100px;

    :deep(.el-alert) {
      border-radius: 0;
      padding: 6px 0;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
}

// 表格行样式
:deep(.el-table) {
  .highlighted-row {
    background-color: rgba(64, 158, 255, 0.08) !important;

    & > td {
      border-top: 2px solid #409eff;
      border-bottom: 2px solid #409eff;
    }

    &:first-child > td {
      border-top: 2px solid #409eff !important;
    }

    &:last-child > td {
      border-bottom: 2px solid #409eff;
    }
  }

  .selected-row {
    background-color: rgba(255, 228, 200, 0.2) !important;
  }
}

// 定位动画
.highlight-animation {
  animation: highlight-pulse 2s ease-in-out 3;
}

@keyframes highlight-pulse {
  0% {
    background-color: rgba(64, 158, 255, 0.1);
  }
  50% {
    background-color: rgba(64, 158, 255, 0.3);
  }
  100% {
    background-color: rgba(64, 158, 255, 0.1);
  }
}
</style>

<style>
/* 全局表格样式 */
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #f0f7ff !important;
}
</style>
